package com.niguang.work.api.weChatTemplate.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.niguang.common.constant.ResultCode;
import com.niguang.common.pojo.Result;
import com.niguang.common.util.DateUtils;
import com.niguang.work.api.entity.DeviceWechatUser;
import com.niguang.work.api.entity.Machine;
import com.niguang.work.api.enums.WechatTemplateEnum;
import com.niguang.work.api.service.IDeviceWechatUserService;
import com.niguang.work.api.service.MachineService;
import com.niguang.work.api.vo.ShiPingDeviceVo;
import com.niguang.work.api.vo.WechatTemplateMsg;
import com.niguang.work.api.weChatTemplate.abstracts.SendWeChat;
import com.niguang.work.api.weChatTemplate.service.MonitorWeChatService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.fluent.Request;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MonitorWeChatServiceImpl extends SendWeChat implements MonitorWeChatService {


    @Resource
    private MachineService machineService;

    @Resource
    private IDeviceWechatUserService deviceWechatUserService;

    /**
     * 查询闸机是否在线状态
     */
    private static final String ZHA_JI_LINE_STATUS_URL = "http://47.106.194.24:6508/door/inlineMacs";

    private static final String SHI_PING_LINE_STATUS_URL = "https://www.gzhuijiangyuan.com/api/monitors/device/site/device/status";


    private static final String FIRST_NAME = "【%s】掉线报警，请及时处理";

    private static final String SITE_NAME_KEY = "siteName";

    private static final String FIRST_NAME_KEY = "firstName";

    private static final String DEVICE_NAME_KEY = "deviceName";


    @Override
    public Boolean sendMonitor() {
        List<Map<String, String>> deviceList = new ArrayList<>();
        List<Map<String, String>> zhaJiDeviceList = getZhaJiDeviceList();
        List<Map<String, String>> shiPingDeviceList = getShiPingDeviceList();
        deviceList.addAll(shiPingDeviceList);
        deviceList.addAll(zhaJiDeviceList);
        List<String> openIdList = getDeviceOpenIdList();
        if (CollectionUtils.isNotEmpty(openIdList) && CollectionUtils.isNotEmpty(deviceList)) {
            openIdList.forEach(p ->
                    deviceList.forEach(d ->
                            buildWeChat(d.get(FIRST_NAME_KEY), d.get(SITE_NAME_KEY), d.get(DEVICE_NAME_KEY), p)));
            return true;
        }
        return false;
    }


    /**
     * 闸机离线信息
     *
     * @return
     */
    private List<Map<String, String>> getZhaJiDeviceList() {
        List<Map<String, String>> deviceList = new ArrayList<>();
        List<Machine> machineList = machineService.queryMachineList();
        if (CollectionUtils.isNotEmpty(machineList)) {
            String getJson = null;
            try {
                getJson = Request.Get(ZHA_JI_LINE_STATUS_URL).execute().returnContent().asString(Charset.forName("UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            List<String> macList = JSONObject.parseObject(getJson, List.class);
            Map<String, List<Machine>> listMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(macList)) {
                listMap = machineList.parallelStream().filter(p -> !macList.contains(p.getMac()) &&
                        StringUtils.isNotBlank(p.getSiteName())).collect(Collectors.groupingBy(Machine::getSiteName));
            }
            if (!ObjectUtils.isEmpty(listMap)) {
                listMap.entrySet().parallelStream().forEach(p -> {
                    List<Machine> machinesList1 = p.getValue();
                    Map<String, String> map = new HashMap<>();
                    map.put(SITE_NAME_KEY, p.getKey());
                    map.put(FIRST_NAME_KEY, String.format(FIRST_NAME, "闸机"));
                    List<String> collect = machinesList1.parallelStream().map(m -> m.getMacName() + "[" + m.getMac() + "]").collect(Collectors.toList());
                    map.put(DEVICE_NAME_KEY, StringUtils.join(collect, ";"));
                    deviceList.add(map);
                });
            }
        }
        return deviceList;
    }


    /**
     * 视频监控离线信息
     *
     * @return
     */
    private List<Map<String, String>> getShiPingDeviceList() {
        List<Map<String, String>> deviceList = new ArrayList<>();
        String getJson = null;
        try {
            getJson = Request.Get(SHI_PING_LINE_STATUS_URL).execute().returnContent().asString(Charset.forName("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Result result = JSONObject.parseObject(getJson, Result.class);
        if (StringUtils.equalsAnyIgnoreCase(ResultCode.SUCCESS.getValue(), result.getCode()) && !ObjectUtils.isEmpty(result.getData())) {
            List<ShiPingDeviceVo> deviceVoList = JSONArray.parseArray(result.getData().toString(), ShiPingDeviceVo.class);
            deviceVoList.forEach(p -> {
                Map<String, String> map = new HashMap<>();
                map.put(SITE_NAME_KEY, p.getSiteName());
                map.put(FIRST_NAME_KEY, String.format(FIRST_NAME, "摄像头"));
                List<ShiPingDeviceVo.DeviceStatusList> statusLists = p.getDeviceStatusList().parallelStream().filter(d -> d.getStatus() == 0).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(statusLists)) {
                    List<String> collect = statusLists.parallelStream().map(d -> d.getDeviceDesc() + "[" + d.getDeviceId() + "]").collect(Collectors.toList());
                    map.put(DEVICE_NAME_KEY, StringUtils.join(collect, ";"));
                    deviceList.add(map);
                }
            });

        } else {
            log.info("微信推送视频接口异常：{}", result);
        }
        return deviceList;
    }


    /**
     * 设备离线推送微信人信息
     *
     * @return
     */
    private List<String> getDeviceOpenIdList() {
        List<String> list = new ArrayList<>();
        List<DeviceWechatUser> deviceWechatUserList = deviceWechatUserService.selectList(null);
        if (CollectionUtils.isNotEmpty(deviceWechatUserList)) {
            list = deviceWechatUserList.parallelStream().map(DeviceWechatUser::getOpenId).collect(Collectors.toList());
        }
        return list;
    }


    /**
     * 构造设备离线微信推送内容
     *
     * @param firstName
     * @param siteName
     * @param deviceName
     * @param openId
     * @return
     */
    private Boolean buildWeChat(String firstName, String siteName, String deviceName, String openId) {
        WechatTemplateMsg wechatTemplateMsg = new WechatTemplateMsg();
        TreeMap<String, TreeMap<String, String>> params = new TreeMap() {
            {
                put("first", WechatTemplateMsg.item(firstName, WechatTemplateEnum.DEVICE_MONITOR_NOTICE.getTemplateColor()));
                put("keyword1", WechatTemplateMsg.item(siteName, WechatTemplateEnum.WECHAT_TEMPLATE_DEFAULT.getDefaultColor()));
                put("keyword2", WechatTemplateMsg.item(deviceName, WechatTemplateEnum.WECHAT_TEMPLATE_DEFAULT.getDefaultColor()));
                put("keyword3", WechatTemplateMsg.item(DateUtils.getNowDateText(DateUtils.YMDHMS_BREAK), WechatTemplateEnum.WECHAT_TEMPLATE_DEFAULT.getDefaultColor()));
                put("remark", WechatTemplateMsg.item("以上设备正处于离线状态，请及时处理！", WechatTemplateEnum.WECHAT_TEMPLATE_REMARK.getDefaultColor()));
            }
        };
        wechatTemplateMsg.setData(params);
        wechatTemplateMsg.setTouser(openId);
        wechatTemplateMsg.setTemplate_id(WechatTemplateEnum.DEVICE_MONITOR_NOTICE.getTemplateId());
        log.info("设备离线推送信息：{}", JSON.toJSONString(wechatTemplateMsg));
        return super.sendWeChatInfo(wechatTemplateMsg);


    }

}
